function formatJSON(str) {
    try {
        return JSON.stringify(JSON.parse(str), null, 2);
    } catch {
        return str;
    }
}

function updateUI(requests) {
    const tbody = document.getElementById('requestsBody');
    tbody.innerHTML = requests.map(req => `
    <tr>
      <td>${req.method}</td>
      <td>${req.type}</td>
      <td><a href="${req.url}" target="_blank">${new URL(req.url).pathname}</a></td>
      <td>${req.response?.status || '-'}</td>
      <td>
        <div class="json-view">${formatJSON(req.response?.body || '')}</div>
        <button onclick="copyToClipboard('${btoa(req.response?.body || '')}')">复制</button>
      </td>
    </tr>
  `).join('');
}

// 复制功能增强
window.copyToClipboard = (base64) => {
    navigator.clipboard.writeText(atob(base64));
};

// 初始化加载
chrome.storage.local.get('requests', ({requests}) => {
    updateUI(requests || []);
});


const tokenDiv = document.getElementById('token');
const copyBtn = document.getElementById('copyBtn');
// 实时更新
chrome.storage.onChanged.addListener((changes) => {
    if (changes.requests) {
        updateUI(changes.requests.newValue);

        chrome.storage.local.get(['token'], (result) => {
            if (result.token) {
                tokenDiv.textContent = result.token;
            }
        });
    }
});

copyBtn.addEventListener('click', () => {
    const token = tokenDiv.textContent;
    navigator.clipboard.writeText(token).then(() => {
        copyBtn.textContent = "Copied!";
        setTimeout(() => {
            copyBtn.textContent = "Copy Token";
        }, 2000);
    });
});
